package com.yykj.image.center.server.controller;

import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.util.LocalStringUtil;
import com.yykj.common.util.LocalUploadFile;
import com.yykj.common.vo.ResultVO;
import com.yykj.image.center.client.dto.ImageMergeDTO;
import com.yykj.image.center.server.util.LocalImageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api/image/tool/")
@Api(tags = {"图片处理相关接口"})
public class ImageController {

    @PostMapping("/avatar")
    @ApiOperation("多张图片生成头像，返回头像oss地址")
    public ResultVO<String> getHeadImage(@RequestBody ImageMergeDTO imageMergeDTO) {
        try {
            File fileDir = new File("./images/");
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            String filename = LocalStringUtil.getUUID() + ".jpg";
            String destFileName = fileDir.getAbsolutePath() + "/" + filename;
            LocalImageUtil.getGroupAvatar(imageMergeDTO.getImages(), destFileName);
            File file = new File(destFileName);
            if (file.exists()) {

                String ss = LocalUploadFile.uploadFile(file);
                if (ss != null) {
                    file.delete();
                }
                return ResultVO.success(ss);
            } else {
                return ResultVO.error("文件生成失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new NormalException(ResultEnums.IMAGE_MERGE_ERROR,
                    ResultEnums.IMAGE_MERGE_ERROR.getMessage() + e.getMessage());
        }
    }

}
